from openpyxl import load_workbook
from math import ceil
import sys
sys.path.append("..")
from functional.utils import SPLIT_FUNC_DICT, JOIN_STR_DICT, EXTRACT_FUNC_DICT
from traceback import format_exc

def load_keywords(keywords_file_name):
	keyword_set = set()
	with open(keywords_file_name, "r", encoding="utf-8") as keywords_file:
		for row in keywords_file:
			row = row.strip("\n")
			if row != "":
				keyword_set.add(row.lower())
	return keyword_set

def contain_keywords(addr, keyword_set):
	addr = addr.lower()
	for i in keyword_set:
		if i in addr:
			return True
	return False

def filter_single_record(record, keyword_set, outside_flag, bind_author_flag, extract_func):
	# 将非目标大学的地址转为外校
	if outside_flag:
		# 转为外校后仍绑定作者
		if bind_author_flag:
			res = []
			for i in record:
				if contain_keywords(i, keyword_set):
					res.append(i)
				else:
					author_list = extract_func(i)
					for author in author_list:
						res.append(f"{author}-外校")

		else:
			res = [i if contain_keywords(i, keyword_set) else "外校" for i in record]
	
	else:
		res = [i for i in record if contain_keywords(i, keyword_set)]

	return res

def filter_func(args):
	try:
		workbook_file_name = args[0]
		output_file_name = args[1]
		sheet_name = args[2]
		row_from = args[3]
		row_to = args[4]
		data_cols = args[5]
		keywords_file_name = args[6]
		outside_flag = args[7]
		signal = args[8]
		signal.emit("启动大学过滤任务\n开始加载EXCEL文件")

		wb = load_workbook(workbook_file_name)
		signal.emit("完成EXCEL文件加载\n开始过滤一作")
		sh = wb[sheet_name]

		keyword_set = load_keywords(keywords_file_name)

		for data_col in data_cols:
			input_col = data_col[1]
			output_col = data_col[2]
			addr_type = data_col[3]
			bind_author_flag = data_col[4]

			split_func = SPLIT_FUNC_DICT[addr_type]
			join_str = JOIN_STR_DICT[addr_type]
			extract_func = EXTRACT_FUNC_DICT[addr_type]

			if row_from > 1:
				sh.cell(row_from-1, output_col).value = data_col[0]

			length = row_to - row_from + 1
			step = ceil(length*0.1)
			for i in range(row_from, row_to+1):
				addr_str = sh.cell(i, input_col).value
				addr = split_func(addr_str)
				addr = filter_single_record(addr, keyword_set, outside_flag, bind_author_flag, extract_func)
				sh.cell(i, output_col).value = join_str.join(addr)

				cnt = i - row_from + 1
				if cnt % step == 0:
					signal.emit(f"{data_col[0]}: {cnt/length*100:.2f}%")
		
		signal.emit("完成大学过滤\n开始写入结果")
		wb.save(output_file_name)
		signal.emit("完成结果写入")

	except Exception as e:
		signal = args[8]
		signal.emit(f"过滤失败：{e}\n追踪信息：{format_exc()}")
